<template>
  <div class="search_message">
    <!-- 搜索 -->
    <el-input
      v-model.trim="input"
      placeholder="搜索"
      prefix-icon="el-icon-search"
      @input="SearchHistorys"
    ></el-input>
    <div class="history">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="消息" name="message">
          <!-- 有记录 -->
          <div class="message" v-if="ShowHistory">
            <template v-if="filterMessage.length != 0">
              <div
                v-for="(messageItem, messageIndex) in filterMessage"
                :key="messageIndex"
                class="messages-sear"
                @click="msgPosition()"
              >
                <!-- 头像 -->
                <el-avatar :size="32"
                  ><img
                    :src="
                      getFriend(messageItem.createBy).avatar &&
                      getFriend(messageItem.createBy).avatar != ''
                        ? getFriend(messageItem.createBy).avatar
                        : DeAvatar
                    "
                    alt=""
                /></el-avatar>
                <!-- 名字 -->
                <div class="message-name">
                  <p class="title">
                    <span>{{ getFriend(messageItem.createBy).nickName }}</span>
                    <span class="title-time">{{ messageItem.createTime }}</span>
                  </p>
                  <p class="message-content">
                    <span
                      v-labelhot="{
                        hWord: input,
                        word: messageItem.msg,
                      }"
                      >{{ messageItem.msg }}</span
                    >
                  </p>
                </div>
              </div>
            </template>

            <!-- 没有搜索到结果 -->
            <div class="empty" v-else>
              <img
                src="@/assets/images/wssjg_img.png"
                alt=""
                width="147"
              />
              <p>未搜索到匹配内容</p>
            </div>
          </div>

          <!-- 默认显示-->
          <div class="empty" v-else>
            <img
              src="@/assets/images/wssjg_img.png"
              alt=""
              width="147"
            />
            <p>搜索匹配内容</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="文件" name="files">
          <!-- 默认 -->
          <div class="files" v-if="fileHistory.length != 0">
            <!-- 面包屑 -->
            <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
                      <el-breadcrumb-item :to="{ path: '/' }"
                        >文件</el-breadcrumb-item
                      >
                      <el-breadcrumb-item>营业执照</el-breadcrumb-item>
                    </el-breadcrumb> -->
            <!-- 文件 -->
            <!-- 有记录 -->
            <template>
              <a
                :href="fileItem.msg"
                :download="fileItem.msg"
                v-for="(fileItem, fileIndex) in filterFile"
                :key="fileIndex"
              >
                <div class="file-paper">
                  <!-- 文件 -->
                  <el-avatar :size="40">
                    <img
                      src="@/assets/images/wj_icons.svg"
                      alt=""
                      v-if="
                        fileItem.msg.endsWith('.pdf') ||
                        fileItem.msg.endsWith('.docx') ||
                        fileItem.msg.endsWith('.ppt') ||
                        fileItem.msg.endsWith('.doc') ||
                        fileItem.msg.endsWith('.pptx') ||
                        fileItem.msg.endsWith('.PDF') ||
                        fileItem.msg.endsWith('.xlsx') ||
                        fileItem.msg.endsWith('.xls') ||
                        fileItem.msg.endsWith('.txt') ||
                        fileItem.msg.endsWith('.key') ||
                        fileItem.msg.endsWith('.numbers') ||
                        fileItem.msg.endsWith('.word')
                      "
                    />
                    <!-- 文件夹 -->
                    <img src="@/assets/images/wjj_icon.svg" alt="" v-else />
                  </el-avatar>
                  <!-- 名字 -->
                  <div class="file-name">
                    <p class="title">
                      <span
                        v-labelhot="{
                          hWord: input,
                          word: getFileName(fileItem.msg),
                        }"
                        >{{ getFileName(fileItem.msg) }}</span
                      >
                    </p>
                    <p class="file-content">
                      <span>
                        {{
                          getFriend(fileItem.createBy) &&
                          getFriend(fileItem.createBy).nickName
                        }}
                        ·</span
                      >
                      <span> {{ fileItem.createTime }}</span>
                    </p>
                  </div>
                </div>
              </a>
            </template>
            <!-- 没有匹配到结果 -->
            <div class="empty" v-if="filterFile.length == 0">
              <img
                src="@/assets/images/wjg_img.png"
                alt=""
                width="147"
                height="150"
              />
              <p>未搜索到匹配内容</p>
            </div>
          </div>

          <!-- 没有记录  -->
          <div class="empty" v-else>
            <img
              src="@/assets/images/wssjg_img.png"
              alt=""
              width="147"
              height="150"
            />
            <p>暂无内容</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="图片与视频" name="images">
          <div class="images">
            <p v-if="this.weekImg.length != 0">本周</p>
            <div class="img demo-image__preview">
              <el-image
                @click="clickImage"
                :preview-src-list="bigImgs"
                v-for="(imgItem, index) in weekImg"
                :key="index"
                :src="imgItem.msg"
                alt=""
              />
            </div>

            <p v-if="this.mothImg.length != 0">本月</p>
            <div class="img demo-image__preview">
              <el-image
                @click="clickImage"
                :preview-src-list="bigImgs"
                v-for="(imgItem, index) in mothImg"
                :key="index"
                :src="imgItem.msg"
                alt=""
              />
            </div>

            <p v-if="this.morningImg.length != 0">更早</p>
            <div class="img demo-image__preview">
              <el-image
                @click="clickImage"
                :preview-src-list="bigImgs"
                v-for="(imgItem, index) in morningImg"
                :key="index"
                :src="imgItem.msg"
                alt=""
              />
            </div>

            <!-- 没有记录 -->
            <div class="empty" v-if="this.imgHistory.length == 0">
              <img
                src="@/assets/images/wssjg_img.png"
                alt=""
                width="147"
                height="150"
              />
              <p>暂无内容</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { getList,getOrderMessageListApi,getName,getImMsgList } from "@/BMViews/api/upload/index.js";
export default {
  name: "chatMessages",
  data() {
    return {
      fit: "fill",
      // 默认头像src\assets\images\defaultAvatar.jpg
      DeAvatar: require("@/assets/images/defaultAvatar.jpg"),
      // 搜索框内容
      input: "",
      content: "",
      activeName: "message",
      ShowHistory: "", //搜索结果的数据
      ShowFileHistory: "", //搜索文件的结果
      //成员列表
      friend: [],
      friendArr: [],
      // isResultShow: false, //控制搜索结果的显示状态
      // 当前聊天的群
      // currentChat: {
      //   name: "",
      //   color: "",
      //   orderNo: "",
      //   cancelTime: "",
      //   members: "",
      //   messages: [],
      // },
      // 聊天的消息
      chatMessages: [],
      // 过滤的消息
      filterMessage: [],
      // 文件记录
      fileHistory: [],
      filterFile: [],
      // 图片记录
      imgHistory: [],
      filterImage: [],
      // 放大图片
      bigImg: false,
      // 大图片
      bigImgs: [],
      // 本周图片
      weekImg: [],
      //本月
      mothImg: [],
      //更早
      morningImg: [],
    };
  },
  props:{
    //当前聊天室信息
    currentChat:{
      type: Object,
      default: ()=>{ return },
    },
    type:{
      type: [Number,String],
      default: '',
    },
  },
  watch: {
    input: {
      immediate: true,
      handler(val) {
        if(!val) return;
        // console.log(this.filConList);
        this.getMsgss();
        // this.filterMessage = this.chatMessages.filter((item) => {
        //   if (!item.msg) return false;
        //   return item.msg.indexOf(val) !== -1;
        // });
        // this.filterFile = this.fileHistory.filter((item) => {
        //   if (!item.msg) return false;
        //   return item.msg.indexOf(val) !== -1;
        // });
      },
    },
    //监听聊天室信息变化
    currentChat:{
      deep: !0,
      immediate: true,
      handler: async function (newValue, oldValue) {
        //获取聊天记录
        if(!newValue?.id) return false;
        console.log('监听圈聊聊天室更新1',newValue)
        this.input = '';
        this.getMessageMember()
        // 判断时间超过三天没，超过就不能显示输入框聊天了
        // let members = newValue.member.filter((item) => {
        //   return item.status != -1;
        // });
		if(newValue.avatarArr){
			this.friendArr = newValue.avatarArr
			return false;
		}
        //获取群成员用户信息
        let userIds = newValue.members?.map(item => (item.userid));

        let userList = await getName({userIds: userIds?.join(',')})
		
        if(userList.code == 200){
          this.friendArr = userList.data
        }

      }
    }
  },
  created() {
    // this.$bus.$on("currentChat", (names, color, orderNo) => {


    // });
    // // 接收成员
    // this.$bus.$on("friendArr", (friendArr) => {
    //   this.friendArr = friendArr;
    // });
  },
  async mounted() {
    // console.log(this.chatMessages);
    // 消息记录
    // this.$bus.$on("historys", (data) => {
    //   this.chatMessages.push(data);
    // });
    // // 图片文件
    // this.$bus.$on("historyImFi", (src, createBy, createTime) => {
    //   if (this.getSuffix(src)) {
    //     // console.log(src, "99999999999999999999999999");
    //     // console.log(this.weekImg);
    //     this.weekImg.unshift({ msg: src });
    //     this.bigImgs.unshift(src);
    //   } else if (this.getFileSuffix(src)) {
    //     // console.log(this.fileHistory);
    //     this.fileHistory.unshift({
    //       msg: src,
    //       createBy: createBy,
    //       createTime: createTime,
    //     });
    //   }
    // });
  },
  methods: {
    async getMsgss(){
      console.log(this.currentChat,'断电2222');
      if(this.type == 1 || this.type == 2){
        const { code, rows } = await getImMsgList({
          // pageNum: 1,
          // pageSize: 10,
          sessionId: this.currentChat.id,
          text: this.input,
        });
        console.log('搜索单聊聊天记录',rows);
        this.filterMessage = rows;
      }else{
        const { code, data } = await getOrderMessageListApi({
          orderNo: this.currentChat.id,
          text: this.input,
          // startTime: "2022-10-21 01:00:00",
          // endTime: "2022-10-24 01:00:00"
        });
        console.log('搜索圈聊聊天记录',data);
        this.filterMessage = data;
      }


    },
    // 图片下载按钮自定义
    clickImage() {
      this.bigImg = true;
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        let downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-download");
        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        }
      });
    },
    cusClickHandler() {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    hideCusBtn(e) {
      let className = e.target.className;
      if (className === "el-icon-download") {
        let imgUrl = document.getElementsByClassName(
          "el-image-viewer__canvas"
        )[0].children[0].src;
        this.downloadImage(imgUrl);
      }
    },
    downloadImage(imgUrl) {
      let tmpArr = imgUrl.split("/");
      let fileName = tmpArr[tmpArr.length - 1];
      window.URL = window.URL || window.webkitURL; //window.webkitURL和window.URL是一样的，window.URL标准定义，window.webkitURL是webkit内核的实现
      let xhr = new XMLHttpRequest();
      xhr.open("get", imgUrl, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          let blob = this.response;
          let fileUrl = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          (document.body || document.documentElement).appendChild(a);
          // console.log(fileUrl, "路径路径");
          a.href = fileUrl;
          window.location.href = fileUrl;
          if ("download" in a) {
            a.download = fileName;
          } else {
            a.setAttribute("download", fileName);
          }
          a.target = "_self";
          a.click();
          a.remove();
        }
      };
      xhr.send();
    },
    // 点击消息记录跳转到相应位置
    msgPosition() {
      // console.log("520");
    },
    // 判断后缀
    getSuffix(message) {
      if (
        message?.endsWith(".jpg") ||
        message?.endsWith(".png") ||
        message?.endsWith(".gif") ||
        message?.endsWith(".jpeg") ||
        message?.endsWith(".JPG") ||
        message?.endsWith(".PNG") ||
        message?.endsWith(".GIF")
      ) {
        return true;
      } else {
        return false;
      }
    },
    getFileSuffix(message) {
      if (
        message?.endsWith(".pdf") ||
        message?.endsWith(".PDF") ||
        message?.endsWith(".ppt") ||
        message?.endsWith(".docx") ||
        message?.endsWith(".zip") ||
        message?.endsWith(".rar") ||
        message?.endsWith(".pptx") ||
        message?.endsWith(".xlsx") ||
        message?.endsWith(".xls") ||
        message?.endsWith(".txt") ||
        message?.endsWith(".doc") ||
        message?.endsWith(".key") ||
        message?.endsWith(".numbers") ||
        message?.endsWith(".exe") ||
        message?.endsWith(".word")
      ) {
        return true;
      } else {
        return false;
      }
    },
    // 获取消息
    async getMessageMember() {
      console.log(this.currentChat,'断电1111111111');
      if(!this.currentChat?.id) return false;
      if(this.type == 1 || this.type == 2){
        const { code, rows } = await getImMsgList({
          // pageNum: 1,
          // pageSize: 10,
          // startTime: "2022-10-21 01:00:00",
          // endTime: "2022-10-24 01:00:00",
          sessionId: this.currentChat.id,
          pageNum: 1,
          pageSize: 1000
        });
        console.log('搜索单聊聊天记录',rows);
        this.chatMessages = rows;
      }else{
        const { code, data } = await getOrderMessageListApi({
          orderNo: this.currentChat.id,
          // startTime: "2022-10-21 01:00:00",
          // endTime: "2022-10-24 01:00:00"
          // startTime: "2022-10-21 01:00:00",
          // endTime: "2022-10-24 01:00:00"
        });
        console.log('搜索圈聊聊天记录',data);
        this.chatMessages = data;
      }
      // 消息
      // this.friend = data.members;
      // this.chatMessages = data;
      // console.log(this.chatMessages);
      // this.filterMessage = this.chatMessages;
      // 如果是文件则放文件记录数组里
      this.fileHistory = this.chatMessages.filter((item) => {
        return (
          item.msg.endsWith(".pdf") ||
          item.msg.endsWith(".ppt") ||
          item.msg.endsWith(".docx") ||
          item.msg.endsWith(".zip") ||
          item.msg.endsWith(".doc") ||
          item.msg.endsWith(".rar") ||
          item.msg.endsWith(".pptx") ||
          item.msg.endsWith(".xlsx") ||
          item.msg.endsWith(".xls") ||
          item.msg.endsWith(".PDF") ||
          item.msg.endsWith(".exe") ||
          item.msg.endsWith(".key") ||
          item.msg.endsWith(".numbers") ||
          item.msg.endsWith(".word") ||
          item.msg.endsWith(".tgz")
        );
      });
      this.fileHistory.reverse();
      this.filterFile = this.fileHistory;
      // console.log(this.fileHistory);
      // 图片
      this.imgHistory = this.chatMessages.filter((item) => {
        return (
          item.msg.endsWith(".jpg") ||
          item.msg.endsWith(".png") ||
          item.msg.endsWith(".gif") ||
          item.msg.endsWith(".jpeg") ||
          item.msg.endsWith(".JPG") ||
          item.msg.endsWith(".PNG") ||
          item.msg.endsWith(".GIF")
        );
      });
      this.imgHistory.reverse();
      console.log(this.imgHistory);
      this.imgHistory.forEach((bigSrc) => {
        this.bigImgs.push(bigSrc.msg);
      });
      // console.log(this.bigImgs);
      let newDate = this.getDate(new Date());
      // 本周
      this.weekImg = this.imgHistory.filter((weekItem) => {
        let weekTime = weekItem.createTime.substring(0, 10);
        let day = this.DateMinus(weekTime, newDate);
        return 0 < day <= 7;
      });
      // 本月
      this.mothImg = this.imgHistory.filter((mothItem) => {
        let mothTime = mothItem.createTime.substring(0, 10);
        let day = this.DateMinus(mothTime, newDate);
        return 8 < day && day < 30;
      });
      // console.log(this.mothImg);
      // 更多
      this.morningImg = this.imgHistory.filter((moringItem) => {
        let morningTime = moringItem.createTime.substring(0, 10);
        let day = this.DateMinus(morningTime, newDate);
        return day > 30;
      });
    },

    handleClick(tab, event) {
      // console.log(tab, event);
    },

    //  搜索消息的改变事件
    SearchHistorys() {
      this.ShowHistory = this.input;
      this.ShowFileHistory = this.input;
      // console.log(this.input);
    },
    //获取文件名称
    getFileName(url) {
      let name = "";
      if (url !== null && url !== "") {
        name = url.substring(url.lastIndexOf("/") + 1);
      } else {
        name = "无";
      }
      return name;
    },

    //转换时间方法
    getDate(date) {
      //date是传过来的时间戳，注意需为13位，10位需*1000
      //也可以不传,获取的就是当前时间
      var time = new Date(date);
      var year = time.getFullYear(); //年
      var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
      var day = ("0" + time.getDate()).slice(-2); //日
      var mydate = year + "-" + month + "-" + day;
      return mydate;
    },
    // 时间天数
    DateMinus(date1, date2) {
      //date1:小日期   date2:大日期
      var sdate = new Date(date1);
      var now = new Date(date2);
      var days = now.getTime() - sdate.getTime();
      var day = parseInt(days / (1000 * 60 * 60 * 24));
      return day;
    },
  },
  // 第二种方法(过滤文件)
  computed: {
    // // 判断是谁发的消息
    getFriend() {
      return (createBy) => {
        // console.log(createBy);
        // console.log(this.friend);
        return this.friendArr.find((FriendItem) => {
          return FriendItem.userId == createBy;
        });
      };
    },
  },

};
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
* {
  margin: 0;
  padding: 0;
}
.search_message ul li {
  list-style: none;
}
::v-deep .el-card__body {
  height: 100%;
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #f87a23;
  border-color: #f87a23;
}
.search_message {
  height: 100%;
  margin: 0 16px;
}
/* 历史记录 */

.history {
  position: relative;
  height: calc(100% - 36px);
  /* overflow-y: auto; */
  overflow: hidden;
}

::v-deep .history .el-tabs__content {
  height: calc(100% - 60px);
  overflow-y: auto;
  scrollbar-width: none;
}
.history >>> .el-tabs .el-tabs__content::-webkit-scrollbar {
  width: 0 !important;
}
::v-deep .history >>> .el-tabs .el-tabs__content .el-tab-pane {
  overflow-y: auto;
  scrollbar-width: none;
}
/* 消息历史记录 */
.history .empty {
  text-align: center;
  height: 92%;
}
.history .empty img {
  margin-top: 100px;
}
.history .empty p {
  font-size: 12px;
  color: #858a91;
  text-align: center;
  margin-top: 40px;
}
.history .message {
  height: 100%;
}
.history .message .messages-sear {
  display: flex;
  font-size: 12px;
  padding: 10px 10px;
  border-radius: 4px;
  cursor: pointer;
}
.history .message .messages-sear:hover {
  background-color: #e7f0ff;
}
.history .messages-sear .message-name {
  margin-left: 10px;
}
.history .messages-sear .message-name .title {
  margin-bottom: 8px;
}
.history .messages-sear .message-name .title span {
  font-size: 12px;
  margin-right: 5px;
  color: #8f959e;
}
.history .messages-sear .message-content span {
  font-size: 14px;
}
.history ul li div {
  margin-left: 4px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
/* 文件记录 */
.history .files {
  height: 100%;
  overflow-y: auto;
}
.history .files .file-paper {
  display: flex;
  font-size: 12px;
  padding: 10px 10px;
  border-radius: 4px;
}
.history .files .file-paper:hover {
  background-color: #e7f0ff;
}
.history .files .file-paper .file-name {
  margin-left: 10px;
}
.history .files .file-paper .file-name .title {
  margin-bottom: 8px;
}
.history .files .file-paper .file-name .title span {
  font-size: 14px;
}
.history .files .file-paper .file-content span {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  color: #8f959e;
}
.history .files .el-breadcrumb {
  margin: 0 auto 10px;
}
/* 图片 */

.history .images {
  padding: 0 auto 6px;
  margin-bottom: 18px;
}
.history .images p {
  font-size: 12px;
  color: #8f959e;
  margin-bottom: 6px;
}
::v-deep .history .images .img {
  margin-bottom: 10px;
}
::v-deep .history .images .img .el-image__inner {
  width: 76px;
  height: 76px;
  margin-right: 10px;
  border-radius: 10px;
  object-fit: cover;
}

/* 滚动条 */
::-webkit-scrollbar {
  /* display: none; */
  /*滚动条整体样式*/
  width: 0px; /*高宽分别对应横竖滚动条的尺寸*/
  /* height: 5px; */
}

::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  /* -webkit-box-shadow: inset 0 0 5px rgba(248, 245, 245, 0.2); */
  background: rgba(0, 0, 0, 0.2);
}

::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  /* -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.3); */
  border-radius: 0;
  /* background: rgba(0, 0, 0, 0); */
}
</style>
